package com.yenlien.traceyun.plant.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.dao.BaseSoilDao;
import com.yenlien.traceyun.business.entity.Equipment;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.EquipmentService;
import com.yenlien.traceyun.common.utils.Tools;
import com.yenlien.traceyun.plant.dao.*;
import com.yenlien.traceyun.plant.dock_device.kebai.KeBaiGetData;
import com.yenlien.traceyun.plant.entity.Farm;
import com.yenlien.traceyun.plant.entity.Plant;
import com.yenlien.traceyun.plant.entity.Reap;
import com.yenlien.traceyun.plant.utils.MathUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Date 2023/8/17
 * @Descript
 */
@Service
public class IotAppService {


    @Autowired
    private ShiJiRuiTongDao shiJiRuiTongDao;

    @Autowired
    private PlantDao plantDao;
    @Autowired
    private FarmDao farmDao;
    @Autowired
    private ReapDao reapDao;
    @Autowired
    private ReapDetailDao reapDetailDao;
    @Autowired
    private BaseSoilDao baseSoilDao;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private KeBaiGetData keBaiGetData;
    @Autowired
    private KeBaiDao keBaiDao;
    @Value("${xinFengXiang.url}")
    private String url;

    @Autowired
    private XinFengXiangDao xinFengXiangDao;



    public JSONObject getDevData(String companyId) {
        if(StringUtils.isBlank(companyId)){
            companyId = UserAuthUtil.getLoginUser().getCompanyId();
        }
        List<Equipment> equipmentList = equipmentService.findByCompanyId(companyId);
        JSONObject result = new JSONObject();
        Map<String, List<Equipment>> listMap = equipmentList.stream().collect(Collectors.groupingBy(Equipment::getType));
        List<JSONObject> jsonList = new ArrayList<>();
        for(String key : listMap.keySet()){
            JSONObject json = new JSONObject();
            json.put("name", key);
            List<Equipment> list = listMap.get(key);
            json.put("total", list.size());
            jsonList.add(json);
        }
        result.put("devState", jsonList);
        result.put("count", jsonList);
        result.put("devList", equipmentList);
        return result;
    }


    public Object getPlotByCompId(String companyId) {
        if(StringUtils.isBlank(companyId)){
            companyId = UserAuthUtil.getLoginUser().getCompanyId();
        }
        return baseSoilDao.getByCompId(companyId);
    }


    public List<Equipment> getAllDev(String companyId){
        if(StringUtils.isBlank(companyId)){
            companyId = UserAuthUtil.getLoginUser().getCompanyId();
        }
        return equipmentService.findByCompanyId(companyId);
    }


    public List<Plant> getPlantBySoilId(String soilId, String plantName) {
        List<Plant> plantList;
//        BaseSoil baseSoil = baseSoilDao.findById(soilId).orElseThrow(() -> new BusinessException("该地块不存在"));
        if(StringUtils.isBlank(plantName)){
            plantList = plantDao.findBySoilId(soilId);
        }else {
            plantList = plantDao.getPlantBySoilId(soilId, plantName);
        }
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for(Plant plant : plantList){
//            List<Farm> farmList = farmDao.findByPlantId(plant.getId()).stream().sorted(Comparator.comparing(Farm::getBeginTime)).collect(Collectors.toList());
            List<Farm> farmList = farmDao.findByPlantId(plant.getId()).stream()
                    .sorted(Comparator.comparing(x -> Integer.valueOf(x.getBeginTime().replaceAll("-", "")))).collect(Collectors.toList());
            plant.setFarmList(farmList);
            if(1 == plant.getReapStatus() || 2 == plant.getReapStatus()){
                List<Reap> reapList = reapDao.findByPlantBatch(plant.getBatch());
                for(Reap reap : reapList){
                    LocalDate beginTime = LocalDate.parse(reap.getBeginTime(), formatter);
                    LocalDate endTime = LocalDate.parse(reap.getEndTime(), formatter);
                    int days = Period.between(beginTime, endTime).getDays();
                    if(days < 0)
                        days = 0;
                    reap.setReapDays(days + 1);
                    JSONObject reapName = reapDetailDao.getReapNameByReapId(reap.getId());
                    reap.setReapName(reapName.getString("reap_name"));
                    reap.setReapPart(reapName.getString("reap_part"));
                }
                plant.setReapList(reapList);
            }else {
                LocalDate plantTime = LocalDate.parse(plant.getPlantTime(), Tools.DATE_TIME_BIAS_FORMATTER);
                Period next = Period.between(plantTime, now);
                plant.setGrowDays(next.getDays());
            }
        }
//        JSONObject object = new JSONObject();
//        object.put("baseSoil", baseSoil);
//        object.put("plantList", plantList);
        return plantList;
    }





    public JSONObject getPlantData(String companyId, String plotId) {
        // 种植和地块数据
        if(StringUtils.isBlank(companyId)){
            companyId = UserAuthUtil.getLoginUser().getCompanyId();
        }
        List<JSONObject> baseSoilList;
        if(StringUtils.isBlank(plotId))
            baseSoilList = baseSoilDao.getByCompId(companyId);
        else
            baseSoilList = baseSoilDao.getByPlotId(plotId);
        JSONObject result = genPlantResult();
        if(CollectionUtils.isEmpty(baseSoilList)){
            return result;
        }
        Double areaCnt = baseSoilList.stream().map(x -> x.getDouble("area")).reduce(0D, Double::sum);
        result.put("areaCnt", MathUtils.df.format(areaCnt));
        result.put("soilNum", baseSoilList.size());

        List<Plant> plantList = plantDao.findByCompanyId(companyId);
        if(CollectionUtils.isEmpty(plantList)){
            return result;
        }
        Double areaPlantCnt = plantList.stream().map(Plant::getPlantArea).map(Double::valueOf).reduce(0D, Double::sum);
        result.put("areaPlantCnt", MathUtils.df.format(areaPlantCnt));
        result.put("areaNotPlantCnt", MathUtils.df.format(areaCnt - areaPlantCnt));
//        result.put("plantNum", plantList.stream().collect(Collectors.groupingBy(Plant::getPlantName)).size());
        result.put("plantNum", plantList.size());

        List<JSONObject> list = new ArrayList<>();
        for(JSONObject baseSoil : baseSoilList){
            JSONObject json = new JSONObject();
            List<Map<String, Object>> maps = new ArrayList<>();
            List<Plant> plantSoilList = plantList.stream().filter(x -> x.getSoilId().equals(baseSoil.getString("id"))).collect(Collectors.toList());
            for (Plant plant : plantSoilList) {
                Map<String, Object> map = new HashMap<>();
                map.put("plantArea", plant.getPlantArea());            // 种植面积
                map.put("jyName", plant.getJyName());
                map.put("plantName", plant.getPlantName());
                map.put("soilRatio", MathUtils.percentage(Double.valueOf(plant.getPlantArea()), baseSoil.getDouble("area")));    // 地块占比
                map.put("allRatio", MathUtils.percentage(Double.valueOf(plant.getPlantArea()), areaCnt));     // 总占比
                maps.add(map);
            }
            json.put("plantList", maps);
            json.put("baseSoil", baseSoil.getString("name"));
            list.add(json);
        }
        result.put("plantData", list);
        return result;
    }





    public JSONObject genPlantResult(){
        JSONObject object = new JSONObject();
        object.put("areaCnt", 0);                                                       // 总面积
        object.put("areaPlantCnt", 0);                                                  // 已种植面积
        object.put("areaNotPlantCnt", object.getDouble("areaCnt"));                // 未种植面积
        object.put("soilNum", 0);                                                       // 地块数量
        object.put("plantNum", 0);                                                       // 品种数量
        object.put("plantData", null);                                                  // 种植数据
        return object;
    }

}
